package com.xiaoyu.client.ui.activity.help;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baidu.location.Poi;
import com.techfansy.moreImageSelected.ImagePicker;
import com.techfansy.moreImageSelected.MoreImageMethod;
import com.techfansy.moreImageSelected.bean.ImageItem;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.seek.SelectedImgAdapter;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.NearbyActivity;
import com.xiaoyu.commonlib.BillionCardConstants;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.ui.widget.ContainsEmojiEditText;
import com.xiaoyu.commonlib.utils.AccessLocation;
import com.xiaoyu.commonlib.utils.ToastUtil;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 发起求助
 */
public class SeekAddActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, SelectedImgAdapter.IDeleteSelectedListener {
    @BindView(R.id.activity_seek_add_title_back_btn)
    ImageView backBtn;//返回按钮
    @BindView(R.id.activity_seek_add_title_send_btn)
    TextView sendBtn;//发布按钮
    @BindView(R.id.activity_seek_add_title_edit)
    ContainsEmojiEditText titleEdit;//title编辑框
    @BindView(R.id.activity_seek_add_title_world_count)
    TextView titleCountTxt;//title编辑框输入字数
    @BindView(R.id.activity_seek_add_content_addition_edit)
    ContainsEmojiEditText contentEdit;//content编辑框
    @BindView(R.id.activity_seek_add_content_addition_world_count)
    TextView contentCountTxt;//content编辑框输入字数
    @BindView(R.id.activity_seek_add_city_txt)
    TextView cityTxx;//城市txt
    @BindView(R.id.activity_seek_add_city_layout)
    RelativeLayout cityBtn;//城市btn
    @BindView(R.id.activity_seek_add_type_btn)
    TextView typeBtn;//求助类别
    @BindView(R.id.activity_select_grid_view)
    GridView mGridView;

    public static final int Locate_Code = 12;
    private SelectedImgAdapter mAdapter;
    private List<ImageItem> mList = new ArrayList<>();//选中的图片list

    private MoreImageMethod moreImageMethod;
    private ImagePicker imagePicker;

    private String typeId;//选择的求助类别id
    private Poi mPoi;//所在位置


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seek_add);
        ButterKnife.bind(this);
        initView();
        moreImageMethod = new MoreImageMethod();
        imagePicker = ImagePicker.getInstance();
        imagePicker.clear();
    }

    private void initView() {
        backBtn.setOnClickListener(this);
        sendBtn.setOnClickListener(this);
        typeBtn.setOnClickListener(this);
        cityBtn.setOnClickListener(this);

        mGridView.setOnItemClickListener(this);

        mAdapter = new SelectedImgAdapter(mList);
        mGridView.setAdapter(mAdapter);
        mAdapter.setIDeleteImg(this);

        titleEdit.addTextChangedListener(onTitleWatcher);
        contentEdit.addTextChangedListener(onContentWatcher);
    }

    @Override
    public void onClick(View v) {
        if (v == backBtn) {//返回
            onBackPressed();
        } else if (v == sendBtn) {//发布
            if (TextUtils.isEmpty(titleEdit.getText().toString())) {
                ToastUtil.showToast(this, "请填写内容");
                return;
            }
            if (TextUtils.isEmpty(typeId)) {
                ToastUtil.showToast(this, "请选择问题分类");
                return;
            }
            //调接口
            showLoading();
            uploadImg();

        } else if (v == typeBtn) {//求助类别选择
            Intent intent = new Intent(this, SeekTypeActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(SeekTypeActivity.SEEK_TYPE_ID, typeId);
            intent.putExtras(bundle);
            startActivityForResult(intent, 100);
        } else if (v == cityBtn) {
            Intent intent = new Intent(this, NearbyActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable(ClientConstants.Select_Location, mPoi);
            intent.putExtras(bundle);
            startActivityForResult(intent, Locate_Code);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA}, 1);
        moreImageMethod.itemClick(SeekAddActivity.this, i, mList, imagePicker);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Locate_Code) {//地址选择
            if (data != null) {
                mPoi = data.getParcelableExtra(ClientConstants.Select_Location);
                cityTxx.setText(mPoi.getName());
            }
        } else {
            //接收回调的图片
            moreImageMethod.onActivityResult(requestCode, resultCode, data, imagePicker, mList, SeekAddActivity.this);
            mAdapter.upDataList(mList);

            //接收选择的求助类别
            if (requestCode == 100 && resultCode == 0 && data != null) {
                if (data.hasExtra(SeekTypeActivity.SEEK_TYPE_ID)) {
                    typeId = data.getStringExtra(SeekTypeActivity.SEEK_TYPE_ID);
                    typeBtn.setText(data.getStringExtra(SeekTypeActivity.SEEK_TYPE_NAME));
                }
            }
        }
    }

    //上传图片值OSS
    private void uploadImg() {
        if (mList.size() == 0) {
            uplaodData("");
        } else {
            for (int i = 0; i < mList.size(); i++) {
                uploadOSSUrl(mList.get(i).getPaths(), mList.get(i).getName(), i);
            }
        }
    }

    private void uploadOSSUrl(String filePath, String objectKey, int position) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        try {
            OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
            PutObjectResult putResult = oss.putObject(put);
            if (position != mList.size() - 1) return;
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < mList.size(); i++) {
                builder.append("https://yikabangb.oss-cn-beijing.aliyuncs.com/" + mList.get(i).getName());
                builder.append(i != mList.size() - 1 ? "," : "");
            }

            uplaodData(builder.toString());//调取接口上传内容

        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
        }
    }

    private void uplaodData(String seekimg) {
        NetworkManager.addSeek(titleEdit.getText().toString(), contentEdit.getText().toString(), seekimg, Integer.parseInt(typeId), cityTxx.getText().toString(), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                dissmissLoading();
                finish();
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                dissmissLoading();
            }
        });
    }

    /**
     * 问题标题编辑框输入监听
     */
    private TextWatcher onTitleWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String count = s.length() + "/50";
            titleCountTxt.setText(count);
        }
    };

    /**
     * 问题内容编辑框输入监听
     */
    private TextWatcher onContentWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String count = s.length() + "/1000";
            contentCountTxt.setText(count);
        }
    };

    @Override
    public void deleteImg(int position) {
        mList.remove(position);
        moreImageMethod.images.remove(position);
        mAdapter.notifyDataSetChanged();
    }
}


